<route lang="yaml">
  meta:
    title: 库存移动
  </route>

<script setup lang="ts">
import { ElMessage, ElMessageBox } from 'element-plus'
import { computed, ref } from 'vue'

// 用户选择的库位
const selectedTargetLocation = ref('')

// 来源数据表格
const sourceData = ref<InventoryItem[]>([
  { id: 'INV001', warehouseName: '中心仓', locationName: 'A区-货架1层', productName: '零件A', quantity: 50 },
  { id: 'INV002', warehouseName: '中心仓', locationName: 'B区-货架2层', productName: '零件B', quantity: 30 },
  { id: 'INV003', warehouseName: '分仓1号', locationName: 'C区-货架3层', productName: '零件C', quantity: 20 },
])
// 所有可用库位选项（用于下拉框）
// 显式指定类型
const locationOptions = computed(() => {
  const locations = sourceData.value.map((i: InventoryItem) => i.locationName)
  return [...new Set(locations)].map(loc => ({
    label: loc,
    value: loc,
  }))
})
// 来源库存数据接口
interface InventoryItem {
  id: string
  warehouseName: string
  locationName: string
  productName: string
  quantity: number
  editableQuantity?: number // 添加可选属性
}

// 组合结果接口
interface CombinedResult {
  newProductId: string // 新商品编号
  newProductName: string // 新商品名称
  totalQuantity: number // 组合后的总数量
}

// 弹窗控制
const combineDialogVisible = ref(false)

// 筛选条件
const selectedWarehouse = ref('')
const selectedLocation = ref('')

// 已选数据
const selectedItems = ref<InventoryItem[]>([])

// 结果数据（初始化为空对象）
const combinedResult = ref<CombinedResult | null>(null)

// 计算属性：筛选后的来源数据
const filteredSourceData = computed(() => {
  return sourceData.value.filter((item) => {
    const matchWarehouse = !selectedWarehouse.value || item.warehouseName === selectedWarehouse.value
    const matchLocation = !selectedLocation.value || item.locationName === selectedLocation.value
    return matchWarehouse && matchLocation
  })
})

// 多选处理
function handleSelectionChange(val: InventoryItem[]) {
  selectedItems.value = val
  updateCombinedResult()
}

// 更新组合结果
// 修改updateCombinedResult方法
function updateCombinedResult() {
  if (selectedItems.value.length === 0) {
    combinedResult.value = null
    return
  }

  const totalQty = selectedItems.value.reduce((sum, item) => {
    const qty = item.editableQuantity ?? 0
    return sum + qty
  }, 0)

  combinedResult.value = {
    newProductId: `COM${Date.now()}`,
    newProductName: '组合商品',
    totalQuantity: totalQty,
  }
}

// 提交组合操作
function submitCombination() {
  if (selectedItems.value.length === 0) {
    ElMessage.warning('请至少选择一条来源数据')
    return
  }

  if (!combinedResult.value) {
    ElMessage.error('组合信息异常，请刷新页面重试')
    return
  }

  ElMessage.success(`成功组合 ${combinedResult.value.totalQuantity} 件 "${combinedResult.value.newProductName}"`)
  combineDialogVisible.value = false
}

// 作业单相关字段和方法（保持不变）

interface ProcessProject {
  id: string // 作业单号
  type: string // 作业类型
  userName: string // 操作人
  status: '待处理' | '进行中' | '已完成' | '已取消' // 操作状态
  createTime: string // 创建时间
}

// 表格数据
const tableData = ref<ProcessProject[]>([
  {
    id: 'PO20240501001',
    type: '拆分加工',
    userName: '张三',
    status: '进行中',
    createTime: '2024-05-01 10:30',
  },
  {
    id: 'PO20240501002',
    type: '组合加工',
    userName: '李四',
    status: '待处理',
    createTime: '2024-05-01 14:20',
  },
  {
    id: 'PO20240502001',
    type: '拆分加工',
    userName: '王五',
    status: '已完成',
    createTime: '2024-05-02 09:15',
  },
])

// 搜索关键词
const searchKeyword = ref('')

// 新增/编辑/删除模拟函数

function handleEdit(row: ProcessProject) {
  ElMessage.info(`确认加工：${row.id}`)
}
async function handleDelete(row: ProcessProject) {
  try {
    await ElMessageBox.confirm(`确定删除作业单【${row.id}】吗？`, '删除确认', {
      confirmButtonText: '确认删除',
      cancelButtonText: '取消',
      type: 'warning',
    })

    const index = tableData.value.findIndex(item => item.id === row.id)
    if (index > -1) {
      tableData.value.splice(index, 1)
      ElMessage.success('删除成功')
    }
  }
  catch {
    ElMessage.info('已取消删除')
  }
}
</script>

<template>
  <div>
    <FaPageMain>
      <!-- 操作栏 -->
      <div class="mb-4 flex justify-between">
        <div class="button-group">
          <el-button type="primary" @click="combineDialogVisible = true">
            <el-icon>
              <Plus />
            </el-icon>
            <span class="ml-1">库存移动</span>
          </el-button>
        </div>

        <div class="search-wrapper">
          <el-input v-model="searchKeyword" placeholder="请输入作业单据号" clearable style="width: 200px;">
            <template #prefix>
              <el-icon>
                <Search />
              </el-icon>
            </template>
          </el-input>
        </div>
      </div>

      <!-- 表格区域 -->
      <div class="table-wrapper">
        <el-table :data="tableData" style="width: 100%;" max-height="calc(100vh - 200px)" :fit="true">
          <el-table-column type="selection" />
          <el-table-column prop="id" label="作业单号" />
          <el-table-column prop="type" label="作业类型" />
          <el-table-column prop="userName" label="操作人" />
          <el-table-column prop="createTime" label="创建时间" />
          <el-table-column prop="status" label="操作状态">
            <template #default="{ row }">
              <el-tag
                :type="row.status === '待处理' ? 'info'
                  : row.status === '进行中' ? 'warning'
                    : row.status === '已完成' ? 'success' : 'danger'
                "
              >
                {{ row.status }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column label="操作" width="150">
            <template #default="{ row }">
              <div class="flex items-center gap-2">
                <el-button type="primary" link @click="handleEdit(row)">
                  确认加工
                </el-button>
                <el-button type="danger" link @click="handleDelete(row)">
                  删除
                </el-button>
              </div>
            </template>
          </el-table-column>
        </el-table>
      </div>

      <!-- 分页 -->
      <div class="pagination-wrapper">
        <el-pagination :page-size="20" :pager-count="11" layout="prev, pager, next" :total="tableData.length" />
      </div>
    </FaPageMain>

    <!-- 库存移动弹窗 -->
    <el-dialog v-model="combineDialogVisible" title="库存移动" width="1200px">
      <div class="p-4">
        <!-- 筛选项 -->
        <div class="mb-4 flex gap-4">
          <el-select v-model="selectedWarehouse" placeholder="选择仓库" clearable style="width: 200px;">
            <!-- 修改所有el-option组件（仓库和库位选择部分） -->
            <el-option
              v-for="item in [...new Set(sourceData.map(i => i.warehouseName))]" :key="String(item)"
              :label="item" :value="item"
            />

            <!-- 库位选择同理修改 -->
          </el-select>

          <el-select v-model="selectedLocation" placeholder="选择库位" clearable style="width: 200px;">
            <!-- 修改所有el-option组件（仓库和库位选择部分） -->
            <el-option
              v-for="item in [...new Set(sourceData.map(i => i.locationName))]" :key="String(item)"
              :label="item" :value="item"
            />

            <!-- 库位选择同理修改 -->
          </el-select>
        </div>

        <!-- 来源数据表格 -->
        <h4 class="mb-2">
          来源数据
        </h4>
        <el-table :data="filteredSourceData" style="width: 100%;" :fit="true" @selection-change="handleSelectionChange">
          <el-table-column type="selection" />
          <el-table-column prop="id" label="库存编号" />
          <el-table-column prop="warehouseName" label="仓库" />
          <el-table-column prop="locationName" label="库位" />
          <el-table-column prop="productName" label="商品名称" />
          <el-table-column prop="quantity" label="数量" />
          <el-table-column label="操作数量">
            <template #default="{ row }">
              <el-input-number
                v-model="row.editableQuantity" :min="0" :max="row.quantity"
                @change="updateCombinedResult"
              />
            </template>
          </el-table-column>
        </el-table>

        <!-- 结果数据展示 -->
        <!-- 是否要做多数据操作呢 -->
        <div class="mt-6 border rounded bg-gray-50 p-4">
          <h4>移动目标</h4>
          <div class="grid grid-cols-3 mt-2 gap-4">
            <!-- 库位选择（下拉框） -->
            <div>
              <label class="text-sm text-gray-600">目标库位</label>
              <el-select v-model="selectedTargetLocation" placeholder="请选择库位" style="width: 100%;">
                <el-option v-for="loc in locationOptions" :key="loc.value" :label="loc.label" :value="loc.value" />
              </el-select>
            </div>
          </div>
        </div>
      </div>

      <!-- 底部按钮 -->
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="combineDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitCombination">确认移动</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<style scoped>
.search-wrapper {
  display: flex;
  gap: 12px;
}

.table-wrapper {
  margin-top: 16px;
  border: 1px solid var(--el-border-color);
  border-radius: 4px;
}

.pagination-wrapper {
  display: flex;
  justify-content: flex-end;
  margin-top: 16px;
}
</style>
